import log from "./logger";
import {createServer, Socket} from 'net';
import {Container} from "./interfaces";
import {EventEmitter} from "../node-test";

class ContainerImpl extends EventEmitter implements Container {
    gClient: Socket

    public init() {
        const server = createServer((client: Socket) => {
            this.gClient = client
            log.info('Container Client remote= %s:%s', client.remoteAddress, client.remotePort);
            // client.setTimeout(500);
            client.on('data', (buffer) => {
                let s = buffer.toString();
                log.info(s);
                let strings = s.split('|');
                this.emit("container", strings[4])
                log.info('container emit:', strings[4]);
            });
            client.on('end', () => {
                log.info('Client disconnected');
                server.getConnections(function (err, count) {
                    log.info('container Remaining Connection:' + count);
                });
            });
            client.on('error', function (err) {
                log.info('container Socket Error:', JSON.stringify(err));
            });
            client.on('timeout', function () {
                log.info('container Socket Timed Out');
            });
        });

        server.listen(12012, function () {
            log.info('Container Server listening: ' + JSON.stringify(server.address()));
            server.on('close', function () {
                log.info('Container Server Terminated');
            });
            server.on('error', function (err) {
                log.info('Container Server Error:', JSON.stringify(err));
            });
        });
    }
}

const container = new ContainerImpl();
export default container;